package com.sun.weekend.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sun.weekend.R;
import com.sun.weekend.base.BaseFragment;
import com.sun.weekend.beans.UserBean;
import com.sun.weekend.util.CacheUtils;
import com.sun.weekend.util.UserProxy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * @author sunleilei
 */

public class UserCenterEditInfoFragment extends BaseFragment implements View.OnClickListener {

    private TextView user_auth;
    private TextView user_name;
    private ImageView user_icon;
    private TextView user_sex;
    private TextView user_birth;
    private TextView user_city;
    static final int UPDATE_SEX = 11;
    static final int UPDATE_ICON = 12;
    static final int GO_LOGIN = 13;
    static final int UPDATE_SIGN = 14;
    static final int EDIT_SIGN = 15;

    public static UserCenterEditInfoFragment newInstance() {

        Bundle args = new Bundle();
        UserCenterEditInfoFragment fragment = new UserCenterEditInfoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onStart() {
        super.onStart();
        user_name.setText(userBean.getUsername());

    }

    @Override
    protected int getLayoutId() {
        return R.layout.usercenter_edit_info;
    }

    @Override
    protected void findViews(View view) {
        user_auth = (TextView) view.findViewById(R.id.user_auth);
        user_name = (TextView) view.findViewById(R.id.user_name);
        user_icon = (ImageView) view.findViewById(R.id.user_icon);
        user_sex = (TextView) view.findViewById(R.id.user_sex);
        user_birth = (TextView) view.findViewById(R.id.user_birth);
        user_city = (TextView) view.findViewById(R.id.user_city);
        user_auth.setOnClickListener(this);
        user_icon.setOnClickListener(this);
        user_sex.setOnClickListener(this);
        user_birth.setOnClickListener(this);
        user_city.setOnClickListener(this);
        UserBean bean = new UserProxy().getCurrentUser();
        Glide.with(mContext).load(bean.getAvstar() != null ? bean.getAvstar().getFileUrl():"").placeholder(R.mipmap.ic_launcher).into(user_icon);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_auth:
                break;
            case R.id.user_icon:
                showAlbumDialog();
                break;
            case R.id.user_sex:
                break;
            case R.id.user_birth:
                break;
            case R.id.user_city:
                break;

        }
    }

    String dateTime;
    AlertDialog albumDialog;

    public void showAlbumDialog() {
        albumDialog = new AlertDialog.Builder(mContext).create();
        albumDialog.setCanceledOnTouchOutside(true);
        View v = LayoutInflater.from(mContext).inflate(
                R.layout.user_select_icon, null);
        albumDialog.show();
        albumDialog.setContentView(v);
        albumDialog.getWindow().setGravity(Gravity.CENTER);

        TextView albumPic = (TextView) v.findViewById(R.id.album_pic);
        TextView cameraPic = (TextView) v.findViewById(R.id.camera_pic);
        albumPic.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                albumDialog.dismiss();
                Date date1 = new Date(System.currentTimeMillis());
                dateTime = date1.getTime() + "";
                getAvataFromAlbum();
            }
        });
        cameraPic.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                albumDialog.dismiss();
                Date date = new Date(System.currentTimeMillis());
                dateTime = date.getTime() + "";
                getAvataFromCamera();
            }
        });
    }

    private void getAvataFromCamera() {
        File f = new File(CacheUtils.getCacheDirectory(mContext, true, "icon")
                + dateTime);
        if (f.exists()) {
            f.delete();
        }
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri uri = Uri.fromFile(f);
        Log.e("uri", uri + "");

        Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        camera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(camera, 1);
    }

    private void getAvataFromAlbum() {
        Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
        intent2.setType("image/*");
        startActivityForResult(intent2, 2);
    }

    String iconUrl;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case UPDATE_SEX:
                    break;
                case UPDATE_ICON:
                    break;
                case UPDATE_SIGN:
                    break;
                case EDIT_SIGN:
                    break;
                case 1:
                    String files = CacheUtils.getCacheDirectory(mContext, true,
                            "icon") + dateTime;
                    File file = new File(files);
                    if (file.exists() && file.length() > 0) {
                        Uri uri = Uri.fromFile(file);
                        startPhotoZoom(uri);
                    } else {

                    }
                    break;
                case 2:
                    if (data == null) {
                        return;
                    }
                    startPhotoZoom(data.getData());
                    break;
                case 3:
                    if (data != null) {
                        Bundle extras = data.getExtras();
                        if (extras != null) {
                            Bitmap bitmap = extras.getParcelable("data");
                            iconUrl = saveToSdCard(bitmap);
                            user_icon.setImageBitmap(bitmap);
                            updateIcon(iconUrl);
                        }
                    }
                    break;
                case GO_LOGIN:
                    break;
                default:
                    break;
            }
        }
    }
    private void updateIcon(String avataPath) {
        if (avataPath != null) {
            final UserBean userBean = new UserProxy().getCurrentUser();
            final BmobFile file = new BmobFile(new File(avataPath));
            if (userBean == null)
                    return;
            file.upload(new UploadFileListener() {
                @Override
                public void done(BmobException e) {
                    userBean.setAvstar(file);
                    userBean.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                        }
                    });
                }
            });
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 360);
        intent.putExtra("outputY", 360);
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);

    }

    public String saveToSdCard(Bitmap bitmap) {
        String files = CacheUtils.getCacheDirectory(mContext, true, "icon")
                + dateTime + "_12.jpg";
        File file = new File(files);
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }
}
